import Suggest from '../../sql/module/suggest/suggest';
import ImgSuggest from '../../sql/module/suggest/img_suggest';
import auth from '../../middlewares/auth';
import { AddSuggest } from '../../validators/suggest';
import { ListValidator, InfoValidator } from '../../validators/public';
import { Op } from 'sequelize';
import { Success, Forbbidend } from '../../code/http-exception';
import sequelize from 'sequelize';

Suggest.hasMany(ImgSuggest);
ImgSuggest.belongsTo(Suggest, { onDelete: 'CASCADE', hooks: true });
Suggest.hasMany(Suggest);
Suggest.belongsTo(Suggest, { onDelete: 'CASCADE' });

const router: Api = new Map()


router.set('/addSuggest', [auth('public'), async (ctx, next) => {
    const v = await new AddSuggest().validate(ctx)
    let step = 0
    let AtUserId = 0
    let title = ''
    const imgs = v.get('body.imgs')
    const SuggestId = v.get('body.SuggestId')
    const UserId = ctx.auth.id
    //SuggestId存在则为子级反馈
    if (SuggestId) {
        let readed = true
        const suggest = await Suggest.findAll({
            where: {
                [Op.or]: {
                    SuggestId,
                    id: SuggestId
                }
            },
            order: [['step', 'DESC']]
        })
        //继承父级部分字段
        const fristSuggest = suggest[0].dataValues
        AtUserId = fristSuggest.AtUserId || fristSuggest.UserId
        title = fristSuggest.title
        step = fristSuggest?.step + 1
        //AtUserId为第一次发布时用户ID即反馈人ID
        //是否为反馈人确认第一条消息的已读状态
        if (AtUserId === UserId) {
            readed = false
        }
        await Suggest.update({
            readed
        }, {
            where: { id: SuggestId }
        })
    }
    const suggest = await Suggest.create({
        title: title || v.get('body.title'),
        content: v.get('body.content'),
        SuggestId,
        step, AtUserId,
        UserId
    })
    const id = suggest.dataValues.id
    if (imgs) {
        await ImgSuggest.bulkCreate(
            imgs.map((item: any) => ({
                url: item,
                SuggestId: id
            })))
    }
    throw new Success()
}])

//管理员查看反馈列表
router.set('/suggestList', [auth('suggestList'), async (ctx, next) => {
    const v = await new ListValidator().validate(ctx)
    const limit = v.get('query.limit')
    const page_index = v.get('query.page_index')
    const where = { SuggestId: null }
    const { rows, count } = await Suggest.findAndCountAll({
        where,
        include: [ImgSuggest, { model: Suggest, attributes: ['UserId', 'AtUserId', 'id'], order: [['Suggest.id', 'DESC']] }],
        limit: limit * 1,
        distinct: true,
        offset: (page_index - 1) * limit,
        order: [['id', 'DESC']]
    })
    throw new Success({ list: rows, total: count })
}])

//管理员查看反馈详情
router.set('/suggestInfo', [auth('suggestInfo'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    const id = v.get('body.id')
    const where = {
        [Op.or]: {
            SuggestId: id,
            id
        }
    }
    const { rows, count } = await Suggest.findAndCountAll({
        attributes: { include: [[sequelize.literal('UserId=' + UserId), 'isSelf']] },
        where,
        include: ImgSuggest,
        order: [['step', 'ASC']]
    })
    throw new Success({ list: rows, total: count })
}])

//我的反馈
router.set('/suggests', [auth('public'), async (ctx, next) => {
    const v = await new ListValidator().validate(ctx)
    const limit = v.get('query.limit')
    const page_index = v.get('query.page_index')
    const UserId = ctx.auth.id
    const where = { SuggestId: null, UserId }
    const rows = await Suggest.findAll({
        where,
        include: ImgSuggest,
        limit: limit * 1,
        offset: (page_index - 1) * limit,
        order: [['id', 'DESC']]
    })
    const count = await Suggest.count({ where })
    throw new Success({ list: rows, total: count })
}])

//用户查看反馈详情
router.set('/suggest', [auth('public'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    const id = v.get('body.id')
    const where = {
        [Op.or]: {
            SuggestId: id,
            [Op.and]: { id, UserId }
        }
    }
    const { rows, count } = await Suggest.findAndCountAll({
        attributes: { include: [[sequelize.literal('UserId=' + UserId), 'isSelf']] },
        where,
        include: ImgSuggest,
        distinct: true,
        order: [['step', 'ASC']]
    })
    if (rows[0]?.dataValues.step === 0) {
        Suggest.update({ readed: true }, {
            where: {
                id: { [Op.in]: rows.map(item => item.dataValues.id) },
                AtUserId: UserId
            }
        })
        throw new Success({ list: rows, total: count })
    }
    else
        throw new Forbbidend('权限不足')
}])

//用户删除反馈
router.set('/suggestDelete', [auth('public'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    await Suggest.destroy({
        where: {
            id: v.get('query.id'),
            UserId
        }
    })
    throw new Success()
}])

//用户未读反馈
router.set('/notRead', [auth('public'), async (ctx, next) => {
    const UserId = ctx.auth.id
    const { rows, count } = await Suggest.findAndCountAll({
        where: {
            readed: 0,
            AtUserId: UserId,
            [Op.not]: { UserId }
        },
        limit: 20
    })
    throw new Success({ list: rows, total: count })
}])

//admin未读反馈
router.set('/notFinish', [auth('suggestList'), async (ctx, next) => {
    const { rows, count } = await Suggest.findAndCountAll({
        where: {
            readed: 0,
            SuggestId: null,
        },
        limit: 20
    })
    throw new Success({ list: rows, total: count })
}])

export { router }